package cn.com.tianpeidong.restaurantadmin.project.admin.user.rest;

import cn.com.tianpeidong.restaurantadmin.common.exception.BusinessException;
import com.alibaba.fastjson.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import cn.com.tianpeidong.restaurantadmin.common.constant.Constants;
import cn.com.tianpeidong.restaurantadmin.common.util.security.ShiroUtils;
import cn.com.tianpeidong.restaurantadmin.common.util.string.StringUtils;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.service.IPermissionService;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.vo.LoginVO;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;

/**
 * @author tianpeidong
 */
@RestController
@RequestMapping("/session")
public class AuthController {

    @Autowired
    private IPermissionService permissionService;

    @PostMapping
    public ResponseEntity auth(@RequestBody LoginVO loginVo) {

        UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getUserName(), loginVo.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                    .path("/{id}")
                    .buildAndExpand(ShiroUtils.getUserId())
                    .toUri();
            return ResponseEntity.created(location).build();
        } catch (AuthenticationException e) {
            String msg = "用户名或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return new ResponseEntity(msg, HttpStatus.UNAUTHORIZED);
        }
    }

    @GetMapping
    public ResponseEntity getPerms() {
        JSONObject infoMap = permissionService.listUserPerms();
        ShiroUtils.getSession().setAttribute(Constants.SESSION_USER_PERMISSION, infoMap);
        return ResponseEntity.ok(infoMap);
    }

    @DeleteMapping
    public ResponseEntity logout() {
        ShiroUtils.logout();
        return ResponseEntity.noContent().build();
    }

}